// server.js
const express = require('express')
const jwt = require('jsonwebtoken')
const bodyParser = require('body-parser')
const cors = require('cors')

const app = express()

app.use(bodyParser.json())
app.use(cors({ origin: 'http://localhost:5173', credentials: true })) // 允许来自 http://localhost:8080 的请求，并允许凭证

const SECRET_KEY = 'your_secret_key'

app.post('/login', (req, res) => {
  const { username, password } = req.body
  // 假设这里进行了用户名和密码的验证
  if (username === 'admin' && password === '123') {
    const token = jwt.sign({ id: 1, username: 'admin' }, SECRET_KEY, {
      expiresIn: '1h',
    })
    res.json({ success: true, token })
  } else {
    res.status(401).json({ success: false, message: 'Invalid credentials' })
  }
})

app.get('/profile', (req, res) => {
  const token = req.headers['authorization']?.split(' ')[1]
  if (token) {
    try {
      const decoded = jwt.verify(token, SECRET_KEY)
      res.json({ user: decoded })
    } catch (err) {
      res.status(401).json({ message: 'Unauthorized' })
    }
  } else {
    res.status(401).json({ message: 'Unauthorized' })
  }
})

app.listen(3000, () => {
  console.log('jwt_Server is running on port 3000')
})
